package com.victor.utils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;

public class OSSUtil {
	// 阿里云API的外网域名
	public static final String ENDPOINT = "";// "oss-cn-shanghai.aliyuncs.com";
	// 阿里云API的密钥Access Key ID
	public static final String ACCESS_KEY_ID = "";
	// 阿里云API的密钥Access Key Secret
	public static final String ACCESS_KEY_SECRET = "";
	// 阿里云API的bucket名称
	public static final String BACKET_NAME = "";// "uploadpicture";
	// 阿里云API的文件夹名称
	public static final String FOLDER = "";

	private static final Logger log = LoggerFactory.getLogger(OSSUtil.class);

	/**
	 *
	 * 上传图片
	 * 
	 * @param file
	 * @return
	 */
	public static String uploadImg2Oss(MultipartFile file) {
		if (file.getSize() > 1024 * 1024 * 20) {
			return "图片太大";// RestResultGenerator.createErrorResult(ResponseEnum.PHOTO_TOO_MAX);
		}
		String originalFilename = file.getOriginalFilename();
		String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
		Random random = new Random();
		String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
		String imgUrl = "";
		try {
			InputStream inputStream = file.getInputStream();
			uploadFile2OSS(inputStream, name);
			imgUrl = getImgUrl(name);
			return imgUrl;// RestResultGenerator.createSuccessResult(name);
		} catch (Exception e) {
			return "上传失败";// RestResultGenerator.createErrorResult(ResponseEnum.PHOTO_UPLOAD);
		}
	}

	/**
	 * 上传图片获取fileUrl
	 * 
	 * @param instream
	 * @param fileName
	 * @return
	 */
	@SuppressWarnings("deprecation")
	private static String uploadFile2OSS(InputStream instream, String fileName) {
		String ret = "";
		try {
			// 创建上传Object的Metadata
			ObjectMetadata objectMetadata = new ObjectMetadata();
			objectMetadata.setContentLength(instream.available());
			objectMetadata.setCacheControl("no-cache");
			objectMetadata.setHeader("Pragma", "no-cache");
			objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
			objectMetadata.setContentDisposition("inline;filename=" + fileName);
			// 上传文件

			OSSClient ossClient = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
			PutObjectResult putResult = ossClient.putObject(BACKET_NAME, FOLDER + fileName, instream, objectMetadata);
			ret = putResult.getETag();
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		} finally {
			try {
				if (instream != null) {
					instream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return ret;
	}

	public static String getcontentType(String FilenameExtension) {
		if (FilenameExtension.equalsIgnoreCase(".bmp")) {
			return "image/bmp";
		}
		if (FilenameExtension.equalsIgnoreCase(".gif")) {
			return "image/gif";
		}
		if (FilenameExtension.equalsIgnoreCase(".jpeg") || FilenameExtension.equalsIgnoreCase(".jpg")
				|| FilenameExtension.equalsIgnoreCase(".png")) {
			return "image/jpeg";
		}
		if (FilenameExtension.equalsIgnoreCase(".html")) {
			return "text/html";
		}
		if (FilenameExtension.equalsIgnoreCase(".txt")) {
			return "text/plain";
		}
		if (FilenameExtension.equalsIgnoreCase(".vsd")) {
			return "application/vnd.visio";
		}
		if (FilenameExtension.equalsIgnoreCase(".pptx") || FilenameExtension.equalsIgnoreCase(".ppt")) {
			return "application/vnd.ms-powerpoint";
		}
		if (FilenameExtension.equalsIgnoreCase(".docx") || FilenameExtension.equalsIgnoreCase(".doc")) {
			return "application/msword";
		}
		if (FilenameExtension.equalsIgnoreCase(".xml")) {
			return "text/xml";
		}
		return "image/jpeg";
	}

	/**
	 * 获取图片路径
	 * 
	 * @param fileUrl
	 * @return
	 */
	public static String getImgUrl(String fileUrl) {
		if (!StringUtils.isEmpty(fileUrl)) {
			String[] split = fileUrl.split("/");
			String url = getUrl(FOLDER + split[split.length - 1]);
			return url;
		}
		return null;
	}

	/**
	 * 获得url链接
	 *
	 * @param key
	 * @return
	 */
	public static String getUrl(String key) {
		// 设置URL过期时间为10年 3600l* 1000*24*365*10
		Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
		// 生成URL
		OSSClient ossClient = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
		URL url = ossClient.generatePresignedUrl(BACKET_NAME, key, expiration);
		if (url != null) {
			return url.toString();
		}
		return null;
	}

	/**
    * 根据key删除OSS服务器上的文件
    * 
    * @param ossClient oss连接
    * @param bucketName 存储空间
    * @param folder 模拟文件夹名 如"qj_nanjing/"
    * @param key Bucket下的文件的路径名+文件名 如："upload/cake.jpg
    */
   public static void deleteFile(String urlString) {
	   String[] split = urlString.split("\\?");
	   int lastIndexOf = split[0].lastIndexOf("/");
	   String substring = split[0].substring(lastIndexOf+1, split[0].length());
	   String key="photo/"+substring;
	  	   
	// 创建OSSClient实例。
	   OSS build = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
	   // 删除文件。
	   build.deleteObject(BACKET_NAME, key);
	// 关闭OSSClient。
	   build.shutdown();
   }

}
